<template>
  <el-form
      ref="ruleFormRef"
      style="max-width: 100%"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
  >
    <el-form-item label="流程名" prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入流程名"/>
    </el-form-item>
    <el-form-item label="流程类型" prop="type">
      <el-select v-model="ruleForm.type"  style="width: 300px" placeholder="流程类型" >
        <el-option
            v-for="type in types"
            :key="type.id"
            :label="type.typeName"
            :value="type.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="notes">
      <el-input v-model="ruleForm.notes" placeholder="请输入备注"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm()">前往流程绘制</el-button>
      <el-button @click="emitCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import axios from "axios";
import {onMounted, reactive, ref, watch} from 'vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import type { Customer } from "@/types/public-xs/Customer.ts";
import { ElMessage } from 'element-plus';
import type {WorkFlow} from "@/types/workflow/WorkFlow.ts";
import router from "@/router";
import request from "@/util/request.ts";

// 定义 validator 类型
type Validator = (
    rule: any,
    value: string,
    callback: (error?: Error) => void
) => void;

type TypeValidator = (
    rule: any,
    value: number,
    callback: (error?: Error) => void
) => void;


const emit = defineEmits(['submit-success', 'cancel']);
let types = ref([])
let type = ref(null)
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  type:type.value,
  name: '',
  notes:''
});
let modifyType = ref(0)
let modifyName = ref('')

const getType = async () => {
  const res = await request.post('workflowDesign/workFlowType/selectAllWorkFlowType')
  types.value = res.data.data
}
//
// 校验工作流类型唯一性
const checkType: TypeValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择流程类型'));
    return;
  }
console.log(value)
  console.log(modifyType.value)
  if (modifyType.value != 0 && value === modifyType.value) {
    callback();
    return;
  }

  request.post(`workflowDesign/workFlow/checkTypeExit?type=${value}`)
      .then(response => {

        if (!response.data.data) {
          callback(new Error('流程类型已存在'));
        } else {
          callback();
        }
      })
      .catch(error => {
        console.error('校验流程类型失败:', error);
        callback(new Error('校验流程类型失败，请稍后重试'));
      });
};

// 校验工作流类型唯一性
const checkName: Validator = (rule, value, callback) => {
  if (value=='') {
    callback(new Error('请填写流程名'));
    return;
  }
  console.log(value)
  console.log(modifyName.value)
  if (modifyName.value != '' && value === modifyName.value) {
    callback();
    return;
  }

  request.post(`workflowDesign/workFlow/checkNameExit?name=${value}`)
      .then(response => {

        if (!response.data.data) {
          callback(new Error('流程名已存在'));
        } else {
          callback();
        }
      })
      .catch(error => {
        console.error('校验流程名失败:', error);
        callback(new Error('校验流程名失败，请稍后重试'));
      });
};

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入流程名', trigger: ['blur', 'change'] },
    { validator: checkName, trigger: ['blur', 'change'] },
  ],
  type: [
    { required: true, message: '请选择流程类型', trigger: ['blur', 'change'] },
    { validator: checkType, trigger: ['blur', 'change'] }
  ],
  notes: [
    { required: false, message: '请输入备注', trigger: ['blur', 'change'] },
  ],

});

const props = defineProps<{
  workflow?: WorkFlow | null;
}>();

//提交的时候验证唯一性
const submitForm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
        console.log(props.workflow)
        if(modifyType.value==0){
          await router.push(
              {
                path: '/home/workflow/add',
                query:{
                  type:ruleForm.type,
                  notes:ruleForm.notes,
                  name:ruleForm.name
                }
              }
          )
        }else{
          const res = await request({
            method: "post",
            url: 'workflowDesign/workFlow/showWorkFlow',
            data: {
              url: props.workflow.url
            },
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
            }
          })

          let xml = res.data.data

          await router.push({path: '/home/workflow/edit',query:{
              xml:xml,
              workFlow:JSON.stringify(props.workflow)
            }})
        }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

onMounted(() => {
  getType()
})

//重置
const resetForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};

const emitCancel = () => {
  emit('cancel');
};

watch(() => props.workflow, (newWorkflow) => {
  if (newWorkflow) {
    Object.assign(ruleForm, {
      ...newWorkflow,
      // createdBy: Number(localStorage.getItem("userId") || "0"),
      // updateId: localStorage.getItem("userId") || ""
    });
    modifyType.value = newWorkflow.type
    modifyName.value = newWorkflow.name
  }
}, { immediate: true });
</script>

<style scoped>
.demo-ruleForm {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-input input[type="number"]::-webkit-inner-spin-button,
.el-input input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.el-input input[type="number"] {
  -moz-appearance: textfield;
}
</style>
